<template>
  <div class="create-post-page">
    <h4>{{ isEditMode ? '编辑文章' : '新建文章' }}</h4>
    <UploaderFile
      action="/upload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
      :beforeUpload="uploadedCheck"
      @file-uploaded="handleFileUploaded"
      :uploaded="uploadedData"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <!-- <span class="scr-only">Loading...</span> -->
          </div>
        </div>
        <h2>正在上传</h2>
      </template>
      <template #uploaded="dataProps">
        <div class="uploaded-area">
          <img :src="dataProps.uploadedData.data.url" />
          <h3>点击重新上传</h3>
        </div>
      </template>
    </UploaderFile>
    <!-- <input type="file" name="file" @change.prevent="handleFileChange" /> -->
    <ValidateForm @form-submit="onFormSubmit">
      <div class="mb-3">
        <label for="" class="form-label">文章标题:</label>
        <ValidateInput
          placeholder="请输入文章标题"
          type="text"
          :rules="titleRules"
          v-model="titleVal"
        ></ValidateInput>
      </div>
      <div class="mb-3">
        <label for="" class="form-label">文章详情:</label>
        <textarea ref="textArea"></textarea>
        <ValidateInput
          placeholder="请输入文章详情"
          row="10"
          tag="textarea"
          type="text"
          v-model="contentVal"
          :rules="contentRules"
        ></ValidateInput>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">
          {{ isEditMode ? '更新文章' : '发表文章' }}
        </button>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue'
import { useStore } from 'vuex'
import { GolbalDataProps, ImageProps, ResponseType, PostProps } from '../store'
import { useRoute, useRouter } from 'vue-router'
import ValidateForm from './ValidateForm.vue'
import ValidateInput, { RulesProp } from './ValidateInput.vue'
import axios from 'axios'
import UploaderFile from './UploaderFile.vue'
import { beforUpLoadCheck } from '@/hooks/helper'
import createMessage from '../hooks/createMessage'
import EasyMDE from 'easymde'

export default defineComponent({
  name: 'CreatePost',
  components: {
    ValidateForm,
    ValidateInput,
    UploaderFile
  },
  setup () {
    const textArea = ref<null | HTMLTextAreaElement>()
    const titleVal = ref('')
    // const titleValue = (val: string) => {
    //   titleVal.value = val
    // }
    const router = useRouter()
    const route = useRoute()
    const isEditMode = !!route.query.id
    const uploadedData = ref()
    const store = useStore<GolbalDataProps>()
    const titleRules: RulesProp = [
      { type: 'required', message: '文章标题不能为空' }
    ]
    const contentVal = ref('')
    // const contentValue = (val: string) => {
    //   contentVal.value = val
    // }
    const contentRules: RulesProp = [
      { type: 'required', message: '文章详情不能为空' }
    ]
    const uploadedCheck = (file: File) => {
      const result = beforUpLoadCheck(file, {
        format: ['image/jpeg', 'image/png'],
        size: 1
      })
      const { passed, error } = result
      // 根据不同的类型返回不同的信息
      if (error === 'format') {
        createMessage('上传图片只能是 JPG/PNG 格式', 'error')
      }
      if (error === 'size') {
        createMessage('上传图片大小不能超过 1MB', 'error')
      }
      return passed
    }
    let imageId = ''
    const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
        console.log(imageId)
      }
    }
    onMounted(() => {
      if (textArea.value) {
        const easyMDEInstance = new EasyMDE({ element: textArea.value })
      }
      if (isEditMode) {
        store
          .dispatch('fetchPost', route.query.id)
          .then((rawData: ResponseType<PostProps>) => {
            const currentPost = rawData.data
            // 如果它存在就复制
            if (currentPost.image) {
              uploadedData.value = { data: currentPost.image }
            }
            titleVal.value = currentPost.title
            contentVal.value = currentPost.content || ''
          })
      }
    })
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user
        if (column) {
          const newPost: PostProps = {
            // id: new Date().getTime(),
            // _id: '',
            title: titleVal.value,
            content: contentVal.value,
            column,
            // createdAt: new Date().toLocaleString(),
            author: _id
          }
          if (imageId) {
            newPost.image = imageId
          }
          const actionName = isEditMode ? 'updatePost' : 'createPost'
          const sendData = isEditMode
            ? {
                id: route.query.id,
                payload: newPost
              }
            : {
                newPost
              }
          store.dispatch('createPost', newPost).then(() => {
            createMessage('发表成功， 2秒后跳转到文章', 'success')
            setTimeout(() => {
              router.push({ name: 'column', params: { id: column } })
            }, 2000)
          })
          // 自动跳转到详情页
          // store.commit('createPost', newPost)
          // router.push({ name: 'column', params: { id: columnId } })
        }
      }
    }
    // const handleFileChange = (e: Event) => {
    //   console.log(e)
    //   // 在这个input组件中，我们可以拿到它选择的 file 对象，也就是文件对象
    //   const target = e.target as HTMLInputElement // 一个 input 框元素
    //   const files = target.files
    //   // 注意这个是一个 files 列表， 也就是 fileList 对象 它是一个 array-link 的 object 的
    //   // 一个类数组的对象,但是不是一个数组，支持选择多个文件，所以它可能有很多个
    //   if (files) {
    //     // 我们拿到它的第一项，就是我们选择的文件
    //     const upoladedFile = files[0]
    //     // 我们来模拟表单的数据，我们可以使用 FormData 对象，这是另外一种针对 XHR2 设计的新数据类型
    //     // 使用 ForData 能够很方便的实现以 JacaScript 创建 HTML
    //     // 表单数据串联化的就是 name=zs&age=13 这种方式
    //     const formData = new FormData() // 是自带的是可以直接使用的
    //     // 通过 append 方法为其附加了 <input> 值
    //     // 我们通过 FormData 对象添加了 input 的值
    //     formData.append(upoladedFile.name, upoladedFile)
    //     axios
    //       .post('/upload', formData, {
    //         headers: {
    //           // 设置请求头
    //           'Content-Type': 'multipart/form-data'
    //         }
    //       })
    //       .then((resp) => {
    //         console.log(resp)
    //       })
    //   }
    // }
    return {
      titleVal,
      titleRules,
      contentVal,
      contentRules,
      onFormSubmit,
      // titleValue,
      // contentValue,
      uploadedCheck,
      handleFileUploaded,
      uploadedData,
      isEditMode,
      textArea
    }
  }
})
</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.uploaded-area {
  position: relative;
}
.uploaded-area:hover h3 {
  display: block;
}
.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>
